package com.chen.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.*;
import java.util.List;
import java.util.Map;

/**
 * @Author: chen
 * @Date: 2021/4/27 2:23 PM
 * @Version 1.0
 */
@Slf4j
@Configuration
@EnableConfigurationProperties(IdProperties.class)
public class IdAutoConfiguration {

    private static IdProperties idProperties;

    public IdAutoConfiguration(IdProperties idProperties) {
        this.idProperties = idProperties;
    }

    public static Boolean check(String idCard, String name) {

        String host = idProperties.getUrl(); // 【1】请求地址 支持http 和 https 及 WEBSOCKET
        String path = idProperties.getPath();// 【2】后缀
        String appcode = idProperties.getAppCode(); // 【3】开通服务后 买家中心-查看AppCode
        try {
            String urlSend = host + path + "?idCard=" + idCard + "&name=" + URLEncoder.encode(name, "UTF-8");// 【5】拼接请求链接
            URL url = new URL(urlSend);
            HttpURLConnection httpURLCon = (HttpURLConnection) url.openConnection();
            httpURLCon.setRequestProperty("Authorization", "APPCODE " + appcode);//格式Authorization:APPCODE (中间是英文空格)
            int httpCode = httpURLCon.getResponseCode();
            if (httpCode == 200) {
                String json = read(httpURLCon.getInputStream());
                log.info("正常请求计费(其他均不计费)");
                log.info("获取返回的json：");
                log.info(json);
                JSONObject jsonObject = JSON.parseObject(json);
                if (jsonObject.get("status").equals("01")) {
                    return true;
                }
            } else {
                Map<String, List<String>> map = httpURLCon.getHeaderFields();
                String error = map.get("X-Ca-Error-Message").get(0);
                if (httpCode == 400 && error.equals("Invalid AppCode `not exists`")) {
                    log.info("AppCode错误 ");
                } else if (httpCode == 400 && error.equals("Invalid Url")) {
                    log.info("请求的 Method、Path 或者环境错误");
                } else if (httpCode == 400 && error.equals("Invalid Param Location")) {
                    log.info("参数错误");
                } else if (httpCode == 403 && error.equals("Unauthorized")) {
                    log.info("服务未被授权（或URL和Path不正确）");
                } else if (httpCode == 403 && error.equals("Quota Exhausted")) {
                    log.info("套餐包次数用完 ");
                } else {
                    log.info("参数名错误 或 其他错误");
                    log.info(error);
                }
            }
        } catch (MalformedURLException e) {
            log.info("URL格式错误");
        } catch (UnknownHostException e) {
            log.info("URL地址错误");
        } catch (Exception e) {
            // 打开注释查看详细报错异常信息
            // e.printStackTrace();
        }
        return false;
    }

    /*
     * 读取返回结果
     */
    private static String read(InputStream is) throws IOException {
        StringBuffer sb = new StringBuffer();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = null;
        while ((line = br.readLine()) != null) {
            line = new String(line.getBytes(), "utf-8");
            sb.append(line);
        }
        br.close();
        return sb.toString();
    }

    public static void main(String[] args) {
        check("360302199802211013", "陈禹");
    }

}
//{"status":"01","msg":"实名认证通过！","idCard":"360302199802211013",
// "name":"陈禹","sex":"男","area":"江西省萍乡市安源区",
// "province":"江西省","city":"萍乡市",
// "prefecture":"安源区","birthday":"1998-02-21",
// "addrCode":"","lastCode":"",
// "traceId":"20210427144026_521eic_07798dca"}
//@Data
//class IdResponse{
//    private String status;
//
//    private String msg;
//
//    private String idCard;
//
//    private String name;
//
//    private String sex;
//
//    private String area;
//
//    private String province;
//
//    private String city;
//
//    private String prefecture;
//
//    private String birthday;
//
//    private String addrCode;
//
//    private String lastCode;
//
//    private String traceId;
//
//
//}
